import ConfirmComponent from 'vuxComponents/confirm'

let $vm
let watcher

export default {
    install(vue) {
        if (!$vm) {
            ConfirmComponent.props.title.required = false;
            const Confirm = vue.extend(ConfirmComponent)
            $vm = new Confirm({
                el: document.createElement('div')
            })
            document.body.appendChild($vm.$el)
        }

        const confirm = {
            confirm(options) {
                // destroy watcher
                watcher && watcher()
                if (typeof options === 'object') {
                    for (let i in options) {
                        if (i == "title") {
                            $vm.$el.querySelector('.weui_dialog_title').innerHTML = options['title'];
                        } else if (i == "content") {
                            $vm.$el.querySelector('.weui_dialog_bd p').innerHTML = options['content'];
                        } else {
                            $vm[i] = options[i];
                        }
                    }
                }
                if (options.onShow || options.onHide) {
                    watcher = $vm.$watch('show', (val) => {
                        val && options.onShow && options.onShow($vm)
                        val === false && options.onHide && options.onHide($vm)
                    })
                }
                if (options.onCancel || options.onConfirm) {
                    watcher = $vm.$watch('confirm', (val) => {
                        val && options.onConfirm && options.onConfirm($vm)
                        val === false && options.onCancel && options.onCancel($vm)
                    })
                }
                $vm.show = true
            }
        }

        // all Vux's plugins are included in this.$vux
        if (!vue.$vux) {
            vue.$vux = {
                confirm
            }
        } else {
            vue.$vux.confirm = confirm
        }

        vue.mixin({
            created: function() {
                this.$vux = vue.$vux
            }
        })
    }
}
